<template>
  <div class="app-container">

    <div class="filter-container">
      <el-cascader class="filter-item"
        v-model="query.selectChannel"
        :options="mapChannel"
        :props="{ expandTrigger: 'hover',value:'id',label:'name' }"
      ></el-cascader>
      <el-button style="margin-left: 10px" @click="queryRecords" type="primary" class="filter-item">查询</el-button>
      <el-button @click="reload" type="danger" class="filter-item">刷新</el-button>
      <el-button @click="openAddDialog" type="primary" class="filter-item">添加</el-button>
      <el-button @click="handleDelete(undefined,undefined)" type="primary" class="filter-item">批量删除</el-button>
      <el-button @click="handleStatus(undefined,undefined,2)" type="primary" class="filter-item">批量下架</el-button>
      <el-button @click="handleTop(undefined,undefined,1)" type="primary" class="filter-item">批量置顶</el-button>
    </div>

      <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      v-horizontal-scroll="'always'"
      @selection-change="handleSelectionChange"
    >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" label="ID" width="80" />
    <el-table-column prop="channel_name" label="频道" width="120" />
    <el-table-column prop="title" label="标题" width="150" />
    <el-table-column prop="res_url" label="资源" width="150" >
      <template slot-scope="scope">
        <img v-if="scope.row.res_url && scope.row.res_type=='pic' " class="table-img" :src="host+scope.row.res_url">
        <img v-else class="table-img" :src="host+scope.row.cover_url">
      </template>
    </el-table-column>
    <el-table-column prop="link" label="点击链接" width="150" />
    <el-table-column prop="status_name" label="是否上架" width="100" />
    <el-table-column prop="is_top_name" label="是否置顶" width="100" />
    <el-table-column prop="created_at" label="创建时间" width="160" />
    <el-table-column fixed="right" label="操作" min-width="200">
      <template slot-scope="scope">
		    <el-button size="mini" type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>

        <el-button v-if="scope.row.status==1" size="mini" type="text" @click="handleStatus(scope.$index, scope.row,2)">下架</el-button>
        <el-button v-else size="mini" type="text" @click="handleStatus(scope.$index, scope.row,1)">上架</el-button>

        <el-button v-if="scope.row.is_top==1" size="mini" type="text" @click="handleTop(scope.$index, scope.row,2)">取消置顶</el-button>
        <el-button v-else size="mini" type="text" @click="handleTop(scope.$index, scope.row,1)">置顶</el-button>

		</template>
    </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="[10, 20, 100, 200]"
      :page-size="pagination.pageSize"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total">
    </el-pagination>

    <el-dialog title="添加广告" v-loading="loading" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" label-width="120px">

       <!-- <el-form-item label="上传图片/视频" >
          <el-upload
            class="avatar-uploader"
            :action="host+'/guard/upload?module=advert'"
            accept=".png,.jpg,.jpeg,.bmp,.mp4,.avi,.mkv,.rmvb,.flv,.f4v"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>-->

        <el-form-item label="上传图片/视频" >
          <el-upload  :class="objClass"
            :action="host+'/guard/upload?module=advert'"
            list-type="picture-card"
            :limit="1"
            :file-list="fileList"
            :on-change="handleChange"
            :on-exceed="exceed"
            :on-success="handleUploadSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove" >
            <i class="el-icon-plus"></i>
          </el-upload>

         <!-- <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>-->

        </el-form-item>

        <el-form-item  v-if="isShowCover" label="文件名">
          <span>{{form.origin_name}}</span>
        </el-form-item>

        <el-form-item v-if="isShowCover" label="上传视频封面" >
          <el-upload
            class="avatar-uploader"
            :action="host+'/guard/upload?module=advert'"
            accept=".png,.jpg,.jpeg,.bmp"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeUpload">
            <img v-if="form.cover_url" :src="host+form.cover_url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="频道">
          <el-cascader
            v-model="form.channel_id"
            :options="mapFormChannel"
            :props="{ expandTrigger: 'hover',value:'id',label:'name' }"
            ></el-cascader>
        </el-form-item>

        <el-form-item label="标题">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <!--<el-form-item label="图片地址">
          <el-input v-model="form.pic_url"></el-input>
        </el-form-item>-->
        <el-form-item label="点击链接">
          <el-input v-model="form.link"></el-input>
        </el-form-item>

        <el-form-item label="上架/下架">
          <el-switch
            v-model="form.status"
            active-color="#409EFF"
            inactive-color="#909399"
            :active-value="1"
            :inactive-value="2"
            >
          </el-switch>
        </el-form-item>

        <el-form-item label="是否置顶">
          <el-switch
            v-model="form.is_top"
            active-color="#409EFF"
            inactive-color="#909399"
            :active-value="1"
            :inactive-value="2"
            >
          </el-switch>
        </el-form-item>

        <el-form-item v-if="isAdd">
          <el-button type="primary" @click="onSubmit('form')">立即创建</el-button>
        </el-form-item>
        <el-form-item v-else>
          <el-button type="primary" @click="onSubmit('form')">修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>



</template>

<script>

import { myGet, myPost } from '@/utils/myUtils'

const urlAdvertLst = '/guard/advert/lst'
const urlAdvertAdd = '/guard/advert/add'
const urlAdvertDel = '/guard/advert/del'
const urlAdvertChange = '/guard/advert/change'
const urlAdvertDetail = '/guard/advert/detail'
const urlAdvertChannel = '/guard/advert/channel/lst?tree=1'

export default {

    data() {
      return {
        selectId:[],
        loading:false,
        host:process.env.VUE_APP_HOST,
        list:[],
        ext:"",
        isShowCover:false,
        isAdd:true,
        dialogFormVisible:false,
        listLoading:false,

        //dialogImageUrl: '',
        //dialogVisible: false,
        objClass: {
          upLoadShow: true,
          upLoadHide: false,
        },


        //imageUrl:'',
        //coverUrl:'',
        mapChannel:[],
        mapFormChannel:[],
        query:{
          selectChannel:[0],
          name:''
        },
        pagination:{
          page:1,
          pageSize:20,
          total:0,
        },

        fileList:[],
        form:{
          id:0,
          channel_id:1,
          title:'',
          res_url:"",
          cover_url:'',
          link:'',
          status:1,
          is_top:2,
          origin_name:""
        },

        upload:{
          module:'advert',
        }
      }
    },
    methods: {

      handleChange(file, fileList) {
        this.objClass.upLoadHide = true;//上传图片后置upLoadHide为真，隐藏上传框
        this.objClass.upLoadShow = false;
      },
      handleRemove(file, fileList) {
        this.objClass.upLoadShow = true;//删除图片后显示上传框
        this.objClass.upLoadHide = false;
      },


      handlePictureCardPreview(file) {
        //this.dialogImageUrl = file.url;
        //this.dialogVisible = true;
      },

      reload(){
        Object.assign(this.$data.query,this.$options.data().query)
        Object.assign(this.$data.pagination,this.$options.data().pagination)
        this.getRecords()
      },

      queryRecords(){
        Object.assign(this.$data.pagination,this.$options.data().pagination)
        this.getRecords()
      },

      getRecords(){
        this.listLoading = true
        const params = Object.assign(this.query,this.pagination)
        myGet(urlAdvertLst,params).then(res=>{
          this.listLoading = false
          if(res.status){
            this.list = res.data.records
            this.pagination.total = res.data.total
          }
        })
      },

      getChannel(){
        myGet(urlAdvertChannel).then(res=>{
          if(res.status){
            this.mapFormChannel = res.data.records.concat()
            this.mapChannel = res.data.records
            this.mapChannel.unshift({'id':0,'name':'全部'})
            this.query.selectChannel =0
          }
        })
      },

      changeSwitch(row){
        myPost(urlAdvertAdd,{ id:row.id, status:row.status }).then(res=>{
          if(res.status){
            this.$message.success(res.msg)
          }
        })
      },
      openAddDialog(){
        this.dialogFormVisible= true
        //this.imageUrl = "";
        this.isShowCover = false;
        Object.assign(this.$data.form,this.$options.data().form)
      },
      closeAddDialog(){
        Object.assign(this.$data.form,this.$options.data().form)
        this.dialogFormVisible= false
        //this.imageUrl = "";
        this.isShowCover = false;
      },
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
              this.dialogFormVisible = true;
              this.loading = true
              myPost(urlAdvertAdd,this.form).then(res=>{
                this.loading = false
                if(res.status){
                  this.dialogFormVisible = false;
                  this.$message.success(res.msg);
                  this.getRecords()
                }
              })
          }
        });
      },
      handleUploadSuccess(res, file) {
        if(res.status){
          this.fileList = [{
            url:res.data.records.url,
            uid:file.uid
          }]
          //this.imageUrl = res.data.records.url
          this.form.res_url = res.data.records.filePath
          console.log(this.form.res_url)
          const video = ['mp4','avi','rmvb','flv','f4v'];
          //如果上传的是视频
          if(video.indexOf(res.data.records.ext)!=-1){
            this.isShowCover = true
          }else{
            this.isShowCover = false
            this.form.cover_url=""
          }
          this.form.origin_name = res.data.records.originName
        }else{
            this.$message.error(res.msg)
        }
      },
      handleCoverSuccess(res, file) {
        if(res.status){
          this.form.cover_url = res.data.records.filePath
        }else{
            this.$message.error(res.msg)
        }
      },
      beforeUpload(file) {
          /*const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isLt2M) {
              this.$message.error('上传头像图片大小不能超过 2MB!');
          }
          return isLt2M;*/
        return true
      },

      exceed(files, fileList){
        this.$message.error('超出视频上传限制')
      },

      handleSelectionChange(val) {
        this.selectId = [];
        val.forEach(item=>{
          this.selectId.push(item.id)
        })
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSizeChange(val) {
        this.pagination.pageSize = val
        this.pagination.page = 1
        this.getRecords()
      },
      handleCurrentChange(val) {
        this.pagination.page  = val
        this.getRecords();
      },

      handleEdit(index,row){
        this.isAdd = false
        let id = [row.id]

        myGet(urlAdvertDetail,{id}).then(res=>{
          if(res.status){
            let advert = res.data.records;
            //如果是视频
            if(advert.res_type=='video'){
              //this.imageUrl = this.host+'/common/image/cover.png'
              //this.coverUrl = this.host+advert.cover_url
              this.fileList = [
                {
                  url:this.host+'/common/image/cover.png',
                  uid:Math.random()
                }
              ]
              this.isShowCover = true
            }else{
              //this.imageUrl = this.host+advert.res_url
              this.isShowCover = false
              this.fileList = [
                {
                  url:this.host+advert.res_url,
                  uid:Math.random()
                }
              ]
            }

            //delete advert.url
            delete advert.status_name
            delete advert.is_top_name
            delete advert.type_name
            delete advert.res_type

            Object.assign(this.form,advert)
            console.log(this.form)
            //this.form.channel_id = [this.form.channel_id]
            this.dialogFormVisible = true
          }
        })
      },

      handleDelete(index,row){

        if(typeof(row) == "undefined" ){
          if(this.selectId.length<=0){
            this.$message.error('请先选择项目！')
            return;
          }
        }

        this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let id = [];
          if(typeof(row) == "undefined" ){
            id = this.selectId
          }else{
            id = [row.id]
          }
          myGet(urlAdvertDel,{id}).then(res=>{
            if(res.status){
              this.$message.success(res.msg)
              this.getRecords()
            }
          })
        });
      },

      handleStatus(index,row,status){

        if(typeof(row) == "undefined" ){
          if(this.selectId.length<=0){
            this.$message.error('请先选择项目！')
            return;
          }
        }

        let tip = status==1?'确定要上架吗?':'确定要下架吗?';
        this.$confirm(tip, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let id = [];
          if(typeof(row) == "undefined" ){
            id = this.selectId
          }else{
            id = [row.id]
          }
          myPost(urlAdvertChange, {status, id}).then(res => {
            if(res.status){
              this.$message.success(res.msg)
              this.getRecords();
            }
          })
        });
      },

      handleTop(index,row,is_top){

        if(typeof(row) == "undefined" ){
          if(this.selectId.length<=0){
            this.$message.error('请先选择项目！')
            return;
          }
        }

        let tip = is_top==1?'确定要置顶吗?':'确定要取消置顶吗?';
        this.$confirm(tip, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          let id = [];
          if(typeof(row) == "undefined" ){
            id = this.selectId
          }else{
            id = [row.id]
          }

          myPost(urlAdvertChange, {is_top, id}).then(res => {
            if(res.status){
              this.$message.success(res.msg)
              this.getRecords();
            }
          })
        });
      },

    },

    mounted() {
      this.getRecords()
      this.getChannel()
    },
}
</script>

<style>

.upLoadShow .el-upload {
  width: 10rem !important;
  height: 10rem !important;
  line-height: 10rem !important;
}

/*当upLoadHide为true时，启用如下样式，即缩略图的样式，若为false则不启用该样式*/
.upLoadHide .el-upload-list--picture-card .el-upload-list__item {
  width: 10rem !important;
  height: 10rem !important;
  line-height: 10rem !important;
}
/*当upLoadHide为true时，启用如下样式，即上传框的样式，若为false则不启用该样式*/
.upLoadHide .el-upload {
  display: none;
}


.table-img{
    width: 50px;
    height: 50px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
